import java.io.*;
import java.util.Scanner;

public class ReadWithScanner {

	private int port;
	private final File fFile;
	
	/**
	 * Constructor.
	 * @param aFileName 
	 * 		Full name of an existing, readable file.
	 * @param port
	 * 		Port number to look up to
	 */
	public ReadWithScanner(String aFileName, int port){
		fFile = new File(aFileName);  
		this.port = port;
	}

	/**
	 * Template method that calls the processLine() method.
	 * @return
	 * 		The line that we are looking for if it exists, null otherwise
	 * @throws FileNotFoundException
	 * 		If aFileName does not exist
	 */
	public final String processLineByLine() throws FileNotFoundException {
		// We use Scanner and not File in order to be able to close it
		Scanner scanner = new Scanner(new FileReader(fFile));
		String found;
		try {
			// Get each line
			while (scanner.hasNextLine()) {
				found = processLine(scanner.nextLine(), port);
				if(found != null) return found;
			}
		} finally {
			// Close the underlaying stream			
			scanner.close();
		}
		
		return null;
	}
	/**
	 * Method that scans the line <i>aLine</i> of the file where there is the string " XX/tcp" where XX is a port number
	 * @param aLine
	 * 		The line of the file to be parsed
	 * @param port
	 * 		The target port number
	 * @return
	 * 		The line if it corresponds to what we are looking for, null otherwise.
	 */
	protected String processLine(String aLine, int port){
		//We use a second Scanner in order to parse the content of each line 
		Scanner scanner = new Scanner(aLine);
		String blub = " " + port + "/tcp";
		String bla = scanner.findInLine(blub);
		
		if(bla != null) {
			scanner.close();
			return aLine;
		} 
		
		return null;
	}
} 